<script setup lang="ts">
import { reactive, watch, watchEffect } from 'vue';
import type { AreaPrickerConfig, optionsItem } from '@/types/pricker';
import { useLargenScreen } from '@/composables/useLargenScreen';

const props = withDefaults(
  defineProps<{ columns: optionsItem[]; modelValue: [prov: string, area: string, district?: string] | [] }>(),
  {
    columns: () => [],
    modelValue: () => [],
  }
);

const emit = defineEmits<{
  (e: 'update:model-value', value: optionsItem[]): void;
  (e: 'onConfirm', value: optionsItem[]): void;
  (e: 'onCurrentPosition'): void;
}>();

// 监听浏览器窗口变化
const [largenScreen] = useLargenScreen();

const areaPricker: AreaPrickerConfig = reactive({
  show: false,
  cascaderValue: '',
  showValue: () => {
    const prov = areaPricker.columns.find((v) => v.text === props.modelValue[0]);
    const area = prov?.children?.find((v) => v.text === props.modelValue[1]);
    const district = area?.children?.find((v) => v.text === props.modelValue[2]);

    const arr: string[] = [];
    if (prov) {
      arr.push(prov.text);
    }
    if (area) {
      arr.push(area.text);
    }
    if (district) {
      arr.push(district.text);
    }
    return arr.join(' . ');
  },
  onConfirm({ selectedOptions }: { selectedOptions: optionsItem[] }) {
    emit('onConfirm', selectedOptions);
    areaPricker.show = false;
  },
  columns: props.columns,
});

watch(
  () => props.columns,
  () => {
    areaPricker.columns = props.columns;
  }
);

watchEffect(() => {
  areaPricker.cascaderValue = props.modelValue[2] || props.modelValue[1] || '';
});
</script>
<template>
  <div class="bg-[#F6F7F8] rounded-[10px] h-[55px] flex items-center justify-between px-4">
    <div class="text-sm font-medium flex items-center cursor-pointer" @click="areaPricker.show = true">
      <span class="mr-1">{{ areaPricker.showValue() || '请选择地区' }}</span>
      <van-icon name="arrow-down" color="#7A7A7A" size="14" />
    </div>
    <div class="text-[#7A7A7A] text-xs flex items-center cursor-pointer" @click="emit('onCurrentPosition')">
      <span class="mr-1">当前位置</span>
      <van-icon name="aim" size="14" color="#000000" />
    </div>
    <!-- 弹框 -->
    <van-popup
      v-model:show="areaPricker.show"
      round
      position="bottom"
      safe-area-inset-bottom
      :lock-scroll="!largenScreen"
    >
      <van-cascader
        v-model="areaPricker.cascaderValue"
        :field-names="{ text: 'text', value: 'text', children: 'children' }"
        title="请选择所在地区"
        :options="areaPricker.columns"
        @close="areaPricker.show = false"
        @finish="areaPricker.onConfirm"
      />
    </van-popup>
  </div>
</template>
